from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.models import User
from cartoon_us.gallery.models import ArtWork, WrittenWork, Comic
from cartoon_us.comment.models import comment

#upload content to the database
def upload(request):
    if request.method == 'POST':

        #creates the path for the image to be saved 
        p='C:/SDD/trunk/image/comics/'+request.POST['title']+'.jpg'

        #creates illustration object and saves it in the database
        if request.POST['type']=='illustration':
            a=ArtWork(genre=request.POST['genre'],
                      title=request.POST['title'],
                      rate=0,votes=0,
                      path='../comics/'+request.POST['title']+'.jpg',
                      of=request.user)
            a.save()
            me=request.user
            me.illustration_set.create(art=a)
            destination=open(p,'wb+')

            #saves the image in the given path
            for chunk in request.FILES['pic'].chunks():
                destination.write(chunk)
            destination.close()

        #creates written work object and saves it in the database    
        if request.POST['type']=='fiction':
            w=WrittenWork(genre=request.POST['genre'],
                          introduction=request.POST['intro'],
                          abstract=request.POST['abstract'],
                          title=request.POST['title'],
                          rate=0,votes=0,
                          of=request.user)
            w.save()
            me=request.user
            me.story_set.create(work=w)
        # creates a comic objcect and saves it in the database
        if request.POST['type']=='comic':
            p='C:/SDD/trunk/image/comics/'+request.POST['title']+'.jpg'
            c=Comic(genre=request.POST['genre'],
                    introduction=request.POST['intro'],
                    abstract=request.POST['abstract'],
                    title=request.POST['title'],
                    rate=0, votes=0,
                    of=request.user,
                    path='../comics/'+request.POST['title']+'.jpg')
            c.save()
            me=request.user
            me.comics_set.create(comic=c)
            destination=open(p,'wb+')

            #saves the image in the given path
            for chunk in request.FILES['pic'].chunks():
                destination.write(chunk)
            destination.close()
        #returns to the user profile of the user who just posted content
        return HttpResponseRedirect('../profile/'+request.user.username)
    else:
        return render_to_response('backend/upload.html')
    
def rateArtWork(request,t_itle):
   if request.user.is_authenticated():
       #rating for a artwork
        k=ArtWork.objects.get(title=t_itle)
        k.rate+=int(request.POST['rate'])
        k.votes+=1
        k.save()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
   return HttpResponseRedirect('../../home')

def rateWrittenWork(request,t_itle):
   if request.user.is_authenticated():
        k=WrittenWork.objects.get(title=t_itle)
        k.rate+=int(request.POST['rate'])
        k.votes+=1
        k.save()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
   return HttpResponseRedirect('../../home')
def rateComic(request,t_itle):
   if request.user.is_authenticated():
        k=Comic.objects.get(title=t_itle)
        k.rate+=int(request.POST['rate'])
        k.votes+=1
        k.save()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
   return HttpResponseRedirect('../../home')
#displays a specific piece of written work
def specificfiction(request,title):
    if request.user.is_authenticated():

        #data list stores all necessary info and pushes it to the html
        data={}
        data['username']=request.user.username
        story=WrittenWork.objects.get(title=title)
        data['story']=story
        com=[]

        #adds all of the comments attatched to the work to 'data'
        for c in comment.objects.all():
            if c.on=='fiction' and c.to==title:
                # this is a comment on a fiction called title
                com.append(c)
        data['comments']=com
        data['top']=sorted(WrittenWork.objects.all(), key=lambda WrittenWork: WrittenWork.vote(), reverse=True)[:2]
        # top fictions
        return render_to_response('fiction/specific_fictions.html',data)
    return HttpResponseRedirect('../home')

#displays a specific illustration, similar to specificfiction
def specificillustration(request,title):
    if request.user.is_authenticated():
        data={}
        data['username']=request.user.username
        art=ArtWork.objects.get(title=title)
        data['art']=art
        com=[]
        for c in comment.objects.all():
            if c.on=='illustration' and c.to==title:
                com.append(c)
        data['comments']=com
        data['top']=sorted(ArtWork.objects.all(), key=lambda ArtWork: ArtWork.vote(), reverse=True)[:2]
        return render_to_response('illustration/specific_illustration.html',data)
    return HttpResponseRedirect('../home')


def specificcomic(request,title):
    if request.user.is_authenticated():
        data={}
        data['username']=request.user.username
        comic=Comic.objects.get(title=title)
        data['comic']=comic
        com=[]
        for c in comment.objects.all():
            if c.on=='comics' and c.to==title:
                # this is a comment on a comic called title
                com.append(c)
        data['comments']=com
        data['top']=sorted(Comic.objects.all(), key=lambda Comic: Comic.vote(), reverse=True)[:2]
        return render_to_response('comics/specific_comics.html',data)
    return HttpResponseRedirect('../home')
